<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="与二值信号量相比，计数信号量可以记录事件发生的次数。并且，还可以使用计数信号量对数量有限的资源进行访问管理。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-使用计数信号量">
<meta property="og:url" content="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="与二值信号量相比，计数信号量可以记录事件发生的次数。并且，还可以使用计数信号量对数量有限的资源进行访问管理。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/time_line.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/counting-time-line.png">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/manage_resource.png">
<meta property="article:published_time" content="2022-12-16T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T14:02:08.622Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/time_line.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/","path":"2022/12/17/FreeRTOS-use-counting-semaphore/","title":"FreeRTOS-使用计数信号量"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-使用计数信号量 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E4%BA%8C%E5%80%BC%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9A%84%E6%97%A0%E6%B3%95%E8%AE%B0%E5%BD%95%E4%BA%8B%E4%BB%B6%E6%AC%A1%E6%95%B0%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%9A"><span class="nav-number">1.</span> <span class="nav-text">1 二值信号量的无法记录事件次数的问题：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E8%AE%A1%E6%95%B0%E4%BF%A1%E5%8F%B7%E9%87%8F"><span class="nav-number">2.</span> <span class="nav-text">2 计数信号量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-%E4%BD%BF%E7%94%A8%E8%AE%A1%E6%95%B0%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%AE%A1%E7%90%86%E6%9C%89%E9%99%90%E6%95%B0%E9%87%8F%E7%9A%84%E8%B5%84%E6%BA%90"><span class="nav-number">3.</span> <span class="nav-text">3 使用计数信号量管理有限数量的资源</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-使用计数信号量 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-使用计数信号量
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-17 00:00:00" itemprop="dateCreated datePublished" datetime="2022-12-17T00:00:00+08:00">2022-12-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>9.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>12 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
与二值信号量相比，计数信号量可以记录事件发生的次数。并且，还可以使用计数信号量对数量有限的资源进行访问管理。
</center>

<span id="more"></span>

<hr>
<h4 id="1-二值信号量的无法记录事件次数的问题："><a href="#1-二值信号量的无法记录事件次数的问题：" class="headerlink" title="1 二值信号量的无法记录事件次数的问题："></a>1 二值信号量的无法记录事件次数的问题：</h4><p>文章<a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/#more">FreeRTOS-使用二值信号量</a>的最后，描述了一个使用二值信号量，在中断处理函数和任务间进行“事件”同步的例子。<br>我们使用按键作为“中断源”，每当按键按下时，设置信号量。任务<code>button_pressed_handler</code>等待信号量（等待按键事件发生），一旦信号量可用，表示等待的“事件”（按键按下）发生了，则做一些相关的工作。</p>
<p>但这个例子存在一个问题：<br>第一次按键事件发生后（中断处理函数中设置了信号量，信号量变为<code>可用</code>状态），任务<code>button_pressed_handler</code>获得信号量（<code>信号量被获取后，由可用状态再次变为不可用状态</code>），恢复运行，并开始执行一些相关处理动作。<br>如果任务<code>button_pressed_handler</code>在执行相关处理过程中，又连续发生了第二次、第三次按键动作（又触发了两次事件）。<br>由于二值信号量，只有<code>可用</code>和<code>不可用</code>状态，第二次按键事件发生时，信号量由<code>不可用</code>变为<code>可用</code>状态。仅接着的第三次按键事件发生后，中断处理函数中同样也是设置信号量，由于当前信号量已经是<code>可用</code>状态，所以设置操作并未起作用，信号量依旧保持<code>可用状态</code>。<br>当任务<code>button_pressed_handler</code>相关处理操作执行完成后，再次获取信号量，由于当前信号量为<code>可用</code>状态，因此可以立刻获取到信号量，并再次执行相关处理工作。但是，此时对于任务<code>button_pressed_handler</code>来说，它只感知到 “事件”发生了一次，但实际上在处理之前已经发生了两次“事件”。上述过程的时间线如下图所示：<br><img src="/2022/12/17/FreeRTOS-use-counting-semaphore/time_line.png"></p>
<p>下面我们用代码复现上述问题，我们使用<code> vTaskDelay(pdMS_TO_TICKS(2000))</code>让任务<code>button_pressed_handler</code>在获取到信号量后等待2 秒，来模拟任务<code>button_pressed_handler</code>在处理相关工作。<br>任务代码为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">button_pressed_handler</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    SemaphoreHandle_t semaphore = (SemaphoreHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 注意，使用portMAX_DELAY，表示如果信号量不可用，则会一直阻塞当前任务，知道信号量可用。</span></span><br><span class="line">        <span class="comment">// 使用portMAX_DELAY，需要在FreeRTOSConfig.h 文件中定义 INCLUDE_vTaskSuspend = 1</span></span><br><span class="line">        <span class="comment">// 正式产品代码最好使用一个超时值，这样异常发生时（中断有问题，没触发），至少能获得超时错误，可以在超时错误中做一些恢复操作。</span></span><br><span class="line">        xSemaphoreTake(semaphore, portMAX_DELAY);</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in task, do something\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 让任务延迟一会，模拟其在处理一些工作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>按键中断和main函数与文章<a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/#more">FreeRTOS-使用二值信号量</a>中的一致：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;semphr.h&quot;</span></span></span><br><span class="line"></span><br><span class="line">SemaphoreHandle_t semaphore;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用二值信号量进行中断事件同步</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 硬件相关初始化</span></span><br><span class="line">    bsp_init();</span><br><span class="line">    </span><br><span class="line">    semaphore = xSemaphoreCreateBinary();</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != semaphore) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(button_pressed_handler, <span class="string">&quot;button_pressed_handler&quot;</span>, <span class="number">100</span>, semaphore, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//按键中断处理函数，寄存器相关代码与硬件相关</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">GPIOTE_IRQHandler</span><span class="params">(<span class="type">void</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line">    <span class="keyword">if</span> ( NRF_GPIOTE-&gt;EVENTS_PORT == <span class="number">1</span> )&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//中断处理函数中要清除event,不然会导致一直产生中断</span></span><br><span class="line">        NRF_GPIOTE-&gt;EVENTS_PORT = <span class="number">0</span>;    </span><br><span class="line"></span><br><span class="line">        <span class="comment">// 确认是按键按下，则设置信号量</span></span><br><span class="line">        <span class="keyword">if</span>(IS_BUTTON_PRESSED(BUTTON_1)) &#123;</span><br><span class="line">            xSemaphoreGiveFromISR(semaphore, &amp;higher_task_woken);</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in interrupt service function, button pressed\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果higher_task_woken=True，表示有更高优先级任务就绪了</span></span><br><span class="line">    <span class="comment">// 我们使用的是抢占式调度，只要有更高优先级的任务就绪，应该让其立刻运行。</span></span><br><span class="line">    <span class="comment">// 下面的代码就是，判断有更高优先级就绪时，就会设置任务切换中断，那么当前中断函数退出后，就会立刻触发任务切换，让最高优先级的就绪任务运行。</span></span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行代码后，我们在2秒内，连续按下三次按键，可以发现任务只处理了两次事件：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">in interrupt service function, button pressed       #第一次按键 </span><br><span class="line">in task, do something                               #任务获取到信号量，执行处理工作（原地延迟了2秒）</span><br><span class="line">in interrupt service function, button pressed       #第二次按键 </span><br><span class="line">in interrupt service function, button pressed       #第三次按键 </span><br><span class="line">in task, do something                               #任务延迟2秒结束后，再次获取信号量，再次执行处理工作。但只执行了这一次，而实际中间有两次按键</span><br></pre></td></tr></table></figure>


<p>上述这种情况，就是二值信号量存在的“弊端”，即无法记录“事件”发生的次数。如果上面例子中“事件”发生的“次数”也是一个重要的数据（例如，每次发生一次“事件”，任务<code>button_pressed_handler</code>都必须有一次对应的处理），那么二值信号量就不再适用。</p>
<p>因此，二值信号量适用于事件发生频率“较低”的场景中，开发者能确定事件发生后，在后续的处理过程中，事件不会在此期间内，再发生超过一次。<br>更简单的情形，就是应用场景不关心事件发生的次数，只关心有没有发送过。这种场景下也可以使用二值信号量。</p>
<h4 id="2-计数信号量"><a href="#2-计数信号量" class="headerlink" title="2 计数信号量"></a>2 计数信号量</h4><p>由于<code>二值信号量</code>的局限性，一般提供信号量功能的系统同时会提供<code>计数信号量</code>功能，其功能和二值信号量一致，但是多了计数功能。上文的问题，使用<code>计数信号量</code>就可以记录下按键事件发生的次数。<br>计数信号量的<strong>设置</strong>和<strong>获取</strong>API 和二值信号量是一样的，区别只是在创建API:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SemaphoreHandle_t <span class="title function_">xSemaphoreCreateCounting</span><span class="params">( UBaseType_t uxMaxCount, </span></span><br><span class="line"><span class="params">                                            UBaseType_t uxInitialCount )</span></span><br></pre></td></tr></table></figure>
<ul>
<li>uxMaxCount：设置计数信号量在被获取前，可以保留的的最大计数值（以上文的例子解释，就是在任务<code>button_pressed_handler</code>执行处理工作期间，按键只要按下的次数小于<code>uxMaxCount</code>，信号量都可以记录下来）。</li>
<li>指定创建后的初始值（例如，如果指定为0，信号量创建后就是不可用状态，调用<code>xSemaphoreTake</code>获取信号量时，就会让任务阻塞。如果指定为2，创建完成后，立刻连续调用2 次<code>xSemaphoreTake</code>，都能成功获取到信号量）。</li>
</ul>
<p><a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/#more">二值信号量</a>一文中，我们解释了FreeRTOS中的二值信号量，实际是用一个长度为1 的消息队列来实现的。 同理，FreeRTOS的<code>计数信号量</code>也是使用消息队列来实现的，只是消息队列的大小为<code>xSemaphoreCreateCounting</code> API 创建<code>计数信号量</code>时指定的<code>uxMaxCount</code>值。消息队列的大小，即表示信号量被获取前最大可以记录的“事件”发生次数。（同样，如文章<a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/#more">二值信号量</a>中所述，这里创建的大小为<code>uxMaxCount</code>的消息队列，实际上除了消息队列的控制块占用内存，消息本身是不占内存的，因为内部指定的每个消息大小为0，所以消息存储所占内存为大小为<code>uxMaxCount * 0 = 0</code>）</p>
<p>对于计数信号量的<strong>设置</strong>与<strong>获取</strong>，原理也是和二值信号量一样：</p>
<ul>
<li>使用信号量<strong>设置</strong>API <code>xSemaphoreGive</code>，就是向<code>计数信号量</code>表示的消息队列中放入一个消息（即信号量计数值加1。如果消息队列已经满了，即已经达到计数信号量能记录的最大值<code>uxMaxCount</code>，则设置不生效，信号量仍旧保持最大计数值状态）。</li>
<li>使用信号量<strong>获取</strong>API <code>xSemaphoreTake</code>，就是从<code>计数信号量</code>表示的消息队列中提取一个消息（只要消息队列中存在消息，就能立刻成功获取到信号量，成功获取后，计数信号量的计数值会减1。如果消息队列为空，则表示信号量不可用，会阻塞当前任务，直到信号量可用，或到达设置的等待超时时间）。</li>
</ul>
<p>我们使用<code>计数信号量</code>来改造上文的按键事件同步的例子，需要改动的代码很少，使用<code>计数信号量</code>首先需要在工程配置文件<code>FreeRTOSConfig.h</code>中添加使用<code>计数信号量</code>的宏定义：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_COUNTING_SEMAPHORES	1</span></span><br></pre></td></tr></table></figure>
<p>之后，修改上文中的main 函数，将创建信号量API，替换成<code>xSemaphoreCreateCounting</code>即可：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;semphr.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 硬件相关初始化</span></span><br><span class="line">    bsp_init();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 将创建二值信号量，修改为创建计数信号量</span></span><br><span class="line">    <span class="comment">// 最大可以保留的“事件发生数”为10，初始信号量计数状态为0--即不可用</span></span><br><span class="line">    <span class="comment">// semaphore = xSemaphoreCreateBinary();</span></span><br><span class="line">    semaphore = xSemaphoreCreateCounting(<span class="number">10</span>, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != semaphore) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(button_pressed_handler, <span class="string">&quot;button_pressed_handler&quot;</span>, <span class="number">100</span>, semaphore, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>程序运行后，在2秒内连续按键三次，可以发现按键按下了三次，任务<code>button_pressed_handler</code>也执行了三次处理。如下所示:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">in interrupt service function, button pressed       #第一次按键 </span><br><span class="line">in task, do something                               #任务获取到信号量，执行处理工作（原地延迟了2秒）</span><br><span class="line">in interrupt service function, button pressed       #第二次按键 </span><br><span class="line">in interrupt service function, button pressed       #第三次按键 </span><br><span class="line">in task, do something                               #任务延迟2秒结束后，再次成功获取信号量，再次执行处理工作。</span><br><span class="line">in task, do something                               #上一个延迟2秒结束后，再次获取信号量，仍旧能立刻获取到信号量，再次执行处理工作。</span><br></pre></td></tr></table></figure>
<p>程序的执行时间线如下图所示：<br><img src="/2022/12/17/FreeRTOS-use-counting-semaphore/counting-time-line.png"></p>
<h4 id="3-使用计数信号量管理有限数量的资源"><a href="#3-使用计数信号量管理有限数量的资源" class="headerlink" title="3 使用计数信号量管理有限数量的资源"></a>3 使用计数信号量管理有限数量的资源</h4><p>目前为止，我们使用的<code>二值信号量</code>以及<code>计数信号量</code>，都是用来作为任务和任务之间（或中断处理程序和任务）同步的工具。这种使用方式有一个明显的特征：<code>任务a</code>中使用<code>xSemaphoreTake</code>来等待信号量（等待某<code>事件A</code>发生），另一个<code>任务b</code>（或中断处理程序）中在<code>事件A</code>发生时使用<code>xSemaphoreGive</code>设置信号量（告诉<code>任务a</code>事件发生了）。</p>
<p>但<code>信号量</code>不仅可以用来在多个任务间“同步事件”，还可以用来管理资源。<br>假设，我们有一个系统，该系统会收到外部访问请求，每次请求都会访问系统内部的某个<code>资源Z</code>。<br>假设我们有<code>2 个资源Z</code>，每次收到请求时，可以访问任意一个<code>资源Z</code>，假设访问<code>资源Z</code>需要<code>1秒</code>时间，<strong>资源Z 在被访问期间内是不允许再被另一个请求同时访问的</strong>。<br>当外部访问请求频率很低时，如1s一次，每次外部请求都能立刻访问到某个<code>资源Z</code>（2个中的任意一个）。<br>但某个时刻(1秒钟内)，突然有3个外部请求，由于系统只有2个<code>资源Z</code>，因此，只能有2个请求能立刻访问到<code>资源Z</code>，而第三个请求必须等前两个请求中的任意一个访问结束，才能去访问<code>资源Z</code>。</p>
<p>诸如上述情况，对有限资源的互斥访问，就可以使用<code>计数信号量</code>来管理。<br>在创建<code>计数信号量</code>的API 中：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SemaphoreHandle_t <span class="title function_">xSemaphoreCreateCounting</span><span class="params">( UBaseType_t uxMaxCount, </span></span><br><span class="line"><span class="params">                                            UBaseType_t uxInitialCount )</span></span><br></pre></td></tr></table></figure>
<p>第二个值指示了信号量创建完成后，它的初始计数值，即表示我们有几个<code>资源Z</code>可用。<br>任何请求，每次访问<code>资源Z</code>前都要使用<code>xSemaphoreTake</code>先获得信号量，能成功获取到信号量则表示当前还有<code>资源Z</code>可供访问，如果获取不到，就表明没有<code>资源Z</code>可以访问了。<br>当获取到信号量后，开始访问<code>资源Z</code>，访问结束后，需要使用<code>xSemaphoreGive</code>设置信号量，可以理解为将获取的<code>资源Z</code>还回去。这样其它请求到来时，才能获取到信号量（只有成功获取到信号量后，才能访问资源）。</p>
<p>对于前面访问<code>资源Z</code>的例子，我们就可以将<code>xSemaphoreCreateCounting</code>第二个参数<code>uxInitialCount</code>设置为<code>2</code>。这样，信号量创建完成后的计数状态就是2，表示有2 个<code>资源Z</code>可用。<br>某个时刻，同时来了3个对<code>资源Z</code>的访问请求:<code>req1</code>、<code>req2</code>、<code>req3</code>。<br>对于每个请求，访问资源前，先使用<code>xSemaphoreTake</code>获取信号量，由于当前信号量的计数状态为2，<code>req1</code>和<code>req2</code>两个请求都可以立刻获取到信号量，从而开始访问<code>资源Z</code>。但当<code>req3</code>请求获取信号量时，此时信号量的计数状态为0，则获取不到信号量，任务就会阻塞。直到<code>req1</code>和<code>req2</code>中的任意一个访问<code>资源Z</code>完成后，重新设置了信号量，<code>req3</code>才能成功获取到信号量，恢复运行并访问<code>资源Z</code>。<br>该过程时间线大致如下图所示：<br><img src="/2022/12/17/FreeRTOS-use-counting-semaphore/manage_resource.png"></p>
<p>需要再次强调的一点是：<strong>对资源Z的访问，要求是互斥访问</strong>。即这里虽然有两个全局共享的<code>资源Z</code>，但<strong>对任意一个<code>资源Z</code>的访问都需要是互斥的，不允许两个任务同时访问同一个资源Z</strong>，所以才需要使用信号量对访问进行管理，如果资源本身允许多个任务同时访问，那就不需要对访问进行管理了。</p>
<p>最后，我们使用代码来模拟上述过程：</p>
<p>首先创建一个信号量来管理对<code>共享资源Z</code>的访问：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">SemaphoreHandle_t semaphore;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">global_resource_init</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 假设我们只有2个 共享资源Z</span></span><br><span class="line">    <span class="comment">// 创建信号量来管理 共享资源Z。</span></span><br><span class="line">    <span class="comment">// 信号量最大计数值，和初始值都应该设置为2，表示这个资源最大有2个，当前存在2个</span></span><br><span class="line">    semaphore = xSemaphoreCreateCounting(<span class="number">2</span>, <span class="number">2</span>);</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">NULL</span> == semaphore) &#123;</span><br><span class="line">        <span class="keyword">return</span> pdFALSE;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> pdTRUE;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>将对资源的访问进行封装，访问前需要先“获取”信号量，访问完成后需要再重新“设置”信号量，即返还资源。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">accessing_resource</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *accessor)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 访问共享资源Z前，需要获取信号量，获取成功，表示当前还有资源可用</span></span><br><span class="line">    <span class="comment">// 使用portMAX_DELAY，表示如果信号量不可用，则会一直阻塞当前任务，直到信号量可用。</span></span><br><span class="line">    <span class="comment">// 使用portMAX_DELAY，需要在工程配置文件FreeRTOSConfig.h 中定义 INCLUDE_vTaskSuspend = 1</span></span><br><span class="line">    <span class="comment">// 正式产品代码最好使用一个超时值，这样异常发生时，还可以获得超时错误，可以在超时错误中做一些恢复操作。</span></span><br><span class="line">    xSemaphoreTake(semaphore, portMAX_DELAY);</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;%s: start accessing resouce!\n&quot;</span>, accessor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 延迟1秒，模拟正在访问资源Z</span></span><br><span class="line">    vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line"></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;%s end resource access!\n&quot;</span>, accessor);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 资源访问完成后，需要将上面获取的信号量“还回去”。这样其它任务还能继续访问这个资源</span></span><br><span class="line">    xSemaphoreGive(semaphore);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>再创建三个任务，来访问<code>资源Z</code>。简单起见，这三个任务的代码都是一致的。可以只实现一个，创建三次，这里为了更清晰，写了三份任务代码:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start task_a\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        accessing_resource(<span class="string">&quot;task_a&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 延迟100ms，模拟正在执行其它操作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">100</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start task_b\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        accessing_resource(<span class="string">&quot;task_b&quot;</span>);     </span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟100ms，模拟正在执行其它操作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">100</span>));   </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_c</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start task_c\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        accessing_resource(<span class="string">&quot;task_c&quot;</span>); </span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟100ms，模拟正在执行其它操作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">100</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后main函数实现：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;semphr.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 共享资源初始化</span></span><br><span class="line">    <span class="keyword">if</span> (pdTRUE == global_resource_init()) &#123;</span><br><span class="line">        <span class="comment">// 创建三个任务，来访问共享资源</span></span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_c, <span class="string">&quot;task_c&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>程序结果如下所示，task_c由于最后运行，当其请求访问资源时，由于仅有的两个资源正在被task_a和task_b访问中，task_c这时是无法获得到信号量的，将被阻塞在请求信号量函数<code>xSemaphoreTake</code>内部。当前面两个任务中任意一个访问结束后，返还了信号量，这时任务task_c就可以访问资源了：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">start task_a</span><br><span class="line">task_a: start accessing resouce!    # task_a运行后可以立刻访问到资源</span><br><span class="line">start task_b</span><br><span class="line">task_b: start accessing resouce!    # task_b运行后也可以立刻访问到资源</span><br><span class="line">start task_c                        # task_c运行后，不能立刻访问到资源，系统只有2 个资源，正在被task_a、task_b访问</span><br><span class="line">task_a end resource access!</span><br><span class="line">task_b end resource access!</span><br><span class="line">task_c: start accessing resouce!    # 前面有任务的资源访问结束了，现在资源又可用了，task_c可以访问资源了</span><br><span class="line">....</span><br></pre></td></tr></table></figure>


<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972

<br>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/" title="FreeRTOS-使用计数信号量">http://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/12/15/FreeRTOS-use-binary-semaphore/" rel="prev" title="FreeRTOS-使用二值信号量">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-使用二值信号量
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/12/18/memory-ordering-cpu-cache/" rel="next" title="cpu cache">
                  cpu cache <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
